package com.sr.interceptor;

import com.sr.annotation.ApiAuth;
import com.sr.constant.Constant;
import com.sr.enums.ResponseCode;
import com.sr.exception.Assert;
import com.sr.exception.BusinessException;
import com.sr.util.JwtTokenUtil;
import com.sr.util.RedisUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author xiaochi
 * @date 2022/4/30 18:31
 * @desc ApiAuthIntercptor
 */
@Component
public class ApiAuthIntercptor extends AbstractBaseInterceptor {

    /**
     * 具体实现
     * @param request
     * @param response
     * @param method
     * @return
     */
    @Override
    protected boolean execute(HttpServletRequest request, HttpServletResponse response, HandlerMethod method) {
        ApiAuth auth = method.getMethodAnnotation(ApiAuth.class);
        if (auth != null && auth.login()) {
            String token = request.getHeader(Constant.User.ACCESS_TOKEN);
            Assert.isTure(token != null && !"".equals(token),new BusinessException(ResponseCode.TOKEN_ERROR));
            Assert.isTure(!JwtTokenUtil.isTokenExpired(token),new BusinessException(ResponseCode.TOKEN_NO_AVAIL));
            String userId = JwtTokenUtil.getSubject(token);
            Assert.isTure(userId != null && !"".equals(userId),new BusinessException(ResponseCode.TOKEN_NO_AVAIL));
            String userToken = RedisUtil.get(Constant.User.USER_TOKEN_KEY + userId);
            Assert.assertNotNull(userToken,new BusinessException(ResponseCode.SYSTEM_USERNAME_OFFLINE));
            Assert.isTure(Objects.equals(token,userToken),new BusinessException(ResponseCode.TOKEN_EXISTS));
            return true;
        }
        return true;
    }
}
